<template>
  <div class="main-body">
    <div class="demo-form-inline">
      <el-form :inline="true">
        <el-form-item label="型号搜索+">
          <el-input v-model="input" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="search"
            @click="searchEquip"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-form">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        style="background: #e2430e"
        @click="newBuilt"
      >新建</el-button>

      <el-table :data="articles" stripe border style="margin-top: 30px">
        <el-table-column type="index" label="序号" width="60px" />
        <el-table-column prop="name" label="型号名称" />
        <el-table-column prop="model" label="型号编号" />
        <el-table-column prop="image" label="设备图片">
          <template #default="scope">
            <el-image
              :src="scope.row.image"
              style="width:30px,height:30px"
              fit="fill"
            />
          </template>
        </el-table-column>
        <el-table-column prop="vmRow" label="货道行" />
        <el-table-column prop="vmCol" label="货道列" />
        <el-table-column prop="channelMaxCapacity" label="设备容量" />
        <el-table-column label="操作" width="150px" align="center">
          <template #default="scope">
            <el-button
              type="text"
              @click="amendEquip(scope.row)"
            >修改</el-button>
            <el-button type="text" @click="delList">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="main-foot">
        <span>共{{ totalCount }}条记录--第{{ params.pageIndex }}/{{
          totalPage
        }}页</span>
        <el-button-group>
          <el-button
            type="primary"
            icon="el-icon-arrow-left"
            @click="changePageIndex1"
          >上一页</el-button>
          <el-button type="primary" @click="changePageIndex2">
            下一页<i class="el-icon-arrow-right" />
          </el-button>
        </el-button-group>
      </div>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="dialog"
      width="800px"
      :before-close="handleClose"
    >
      <el-form
        ref="typeform"
        :model="addForm"
        label-width="140px"
        class="add-form"
        :rules="rules"
      >
        <el-form-item label="型号名称：" prop="name">
          <el-input
            v-model="addForm.name"
            type="text"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="型号编码：" prop="model">
          <el-input
            v-model="addForm.model"
            type="text"
            placeholder="请输入 (限制数字、字母、中划线、下划线)"
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="货道行数：" prop="vmRow">
          <el-input-number
            v-model="addForm.vmRow"
            controls-position="right"
            :min="1"
            :max="10"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="货道列数：" prop="vmCol">
          <el-input-number
            v-model="addForm.vmCol"
            controls-position="right"
            :min="1"
            :max="10"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="货道容量：" prop="channelMaxCapacity">
          <el-input-number
            v-model="addForm.channelMaxCapacity"
            controls-position="right"
            :min="1"
            :max="10"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="设备图片：" prop="image">
          <el-upload
            :headers="{ Accept: 'application/json,text/plain, */*' }"
            name="fileName"
            class="avatar-uploader"
            action="http://likede2-admin.itheima.net/likede/api/vm-service/sku/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="addForm.image" :src="addForm.image" class="avatar">
            <i v-else class="el-icon-upload2 avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">
              支持扩展名：jpg、png，文件不得大于100kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="equipSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEquipType, postNewSure, xiugaiSure } from '@/api/equipment/manage'
export default {
  name: 'ManagePage',
  components: {},
  props: {},
  data() {
    const validateModel = (rule, value, callback) => {
      const reg = /^[A-Za-z0-9_-]{1,}$/
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error('请输入合法的型号编码'))
      }
    }
    return {
      title: null,
      input: '',
      articles: [],
      totalCount: '', // 记录的数量
      totalPage: '',
      params: {
        pageIndex: 1,
        pageSize: 10
      },
      dialog: false,
      typeId: null,
      addForm: {
        name: '',
        model: '',
        vmRow: null,
        vmCol: null,
        channelMaxCapacity: null,
        image: ''
      },
      imageUrl: '',
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        model: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: validateModel, trigger: 'blur' }
        ],
        vmRow: [{ required: true, message: '请输入', trigger: 'blur' }],
        vmCol: [{ required: true, message: '请输入', trigger: 'blur' }],
        channelMaxCapacity: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        image: [{ required: true, message: '请上传', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getEquipType()
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    // 列表渲染
    async getEquipType() {
      const res = await getEquipType(this.params)
      console.log(res)
      this.totalCount = res.totalCount
      this.totalPage = res.totalPage
      this.articles = res.currentPageRecords
    },
    // 页面减一
    changePageIndex1() {
      if (this.params.pageIndex > 1) {
        this.params.pageIndex = this.params.pageIndex - 1
      }
      this.getEquipType()
    },
    // 页面加一
    changePageIndex2() {
      if (this.params.pageIndex < this.totalPage) {
        this.params.pageIndex = this.params.pageIndex + 1
      }
      this.getEquipType()
    },
    async searchEquip() {
      this.params.name = this.input
      const res = await getEquipType(this.params)
      this.articles = res.currentPageRecords
    },
    // 上传图片插件
    handleAvatarSuccess(res, file) {
      this.addForm.image = res
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt200kb = (file.size / 1024 / 1024 / 1024) * 100 < 200

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt200kb) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt200kb
    },
    // 新建
    newBuilt() {
      this.title = '新增设备类型'
      this.addForm = {
        name: '',
        model: '',
        vmRow: null,
        vmCol: null,
        channelMaxCapacity: null,
        image: ''
      }
      this.dialog = true
    },
    // 修改
    async amendEquip(row) {
      console.log(row)
      this.title = '修改设备类型'
      this.addForm = row
      this.typeId = row.typeId
      this.dialog = true
    },
    // 确定
    async equipSure() {
      try {
        await this.$refs.typeform.validate()
        if (this.title === '新增设备类型') {
          await postNewSure(this.addForm)
          this.$message.success('添加成功')
        } else {
          await xiugaiSure(this.addForm, this.typeId)
          this.$message.success('修改成功')
        }
      } catch (error) {
        console.log(error)
        // if (error.response.data) {
        //   this.$message.error(error.response.data)
        // }
      }
      this.dialog = false
    },
    // 删除
    delList() {
      this.$notify({
        title: '消息',
        message: '演示系统，不支持此操作',
        type: 'warning'
      })
    }
  }
}
</script>

<style scoped lang="scss">
// 渲染列表
::v-deep .el-image__inner {
  width: 30px;
  height: 30px;
}
// 下页
.main-foot {
  margin-top: 20px;
  height: 36px;
  display: flex;
  justify-content: space-between;
  span {
    line-height: 36px;
    font-size: 14px;
  }
  ::v-deep .el-button-group > .el-button:first-child {
    height: 36px;
  }
  ::v-deep .el-button-group > .el-button:last-child {
    height: 36px;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
